package com.example.windows8.newef.util;

import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;
import android.widget.TextView;

/**
 * Created by windows8 on 2017/11/28.
 * 输入框监听
 */

public class CriTextWatcher implements TextWatcher {
    private int editStart;
    private int editEnd;
    private EditText content;
    private TextView textnum;
    //输入框字数限制
    private static final int WEIBO_CONTENT_LENGTH_LIMITED = 150;
    public CriTextWatcher(EditText content,TextView textnum){
        this.content = content;
        this.textnum = textnum;
    }

    @Override
    public void afterTextChanged(Editable s) {
        editStart = content.getSelectionStart();
        editEnd = content.getSelectionEnd();
        // 先去掉监听器，否则会出现栈溢出
        content.removeTextChangedListener(this);
        while (content.getText().toString().length() > WEIBO_CONTENT_LENGTH_LIMITED) {
            s.delete(editStart - 1, editEnd);
            editStart--;
            editEnd--;
        }
        content.setText(s);
        content.setSelection(editStart);
        content.addTextChangedListener(this);
        textnum.setText(content.getText().length()+"");
    }
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
}
